#!/usr/bin/python
# -*- coding:utf-8 -*-
import arcpy
import csv

##################################################################
arcpy.env.workspace = u"E:\\0S-lab\\0slab项目\\10襄阳\\DATA.gdb\\"
arcpy.env.overwriteOutput = True

outdb = u"E:\\0S-lab\\0slab项目\\10襄阳\\test.gdb\\"

shppath = u"E:\\0S-lab\\0slab项目\\10襄阳\\testc\\"
shps = [u"all2008.shp", u"all2015.shp", u"all2017.shp"]

filepath = u"E:\\0S-lab\\0slab项目\\10襄阳\\multicenter\\out\\DBSCAN_100_20\\"
filenames = [u"all2008out.csv", u"all2015out.csv", u"all2017out.csv"]

# 连接表
# Replace a layer/table view name with a path to a dataset (which can be a layer file) or create the layer/table view within the script
# The following inputs are layers or table views: "all2008", "all2008out.csv"
# arcpy.AddJoin_management(in_layer_or_view=shps[0], in_field="ID", join_table= filepath + filenames[0], join_field="id", join_type= "")

# 将shp转为feature class
for i in shps:
    if not arcpy.Exists(shppath + i):
        print "不存在该数据" + i
        break
    else:
        if arcpy.Exists(outdb + i.split(".shp")[0]):
            arcpy.DeleteFeatures_management(outdb + i.split(".shp")[0])
        arcpy.FeatureClassToFeatureClass_conversion(shppath + i, outdb, i.split(".shp")[0])

# 将csv转为表
intable = []
for i in filenames:
    if not arcpy.Exists(filepath + i):
        print "不存在表格" + i
        break
    else:
        if arcpy.Exists(outdb + i):
            arcpy.DeleteFeatures_management(outdb + i)
        intable.append(filepath + i)
arcpy.TableToGeodatabase_conversion(Input_Table = intable, Output_Geodatabase = outdb)

# 取中心点
for i in range(0, len(shps)):
    infeature = outdb + shps[i].split(".shp")[0]
    intable = outdb + filenames[i].split(".csv")[0]
    arcpy.JoinField_management(in_data= infeature, in_field="ID", join_table= intable, join_field="id", fields="cluster")
    outcentral = outdb + filenames[i].split(".csv")[0]+"_central"
    arcpy.CentralFeature_stats(infeature, outcentral, "EUCLIDEAN_DISTANCE", "#", "#", "cluster")

    print 'Export attributes table...'
    csvFileName = filepath + filenames[i].split(".csv")[0] + "central.csv"
    writeFile = open(csvFileName, "wb")
    writeFileHandle = csv.writer(writeFile)
    outputHeader = ['cluster', 'POINT_X', 'POINT_Y']
    writeFileHandle.writerow(outputHeader)
    searchCur = arcpy.SearchCursor(outcentral)
    for row in searchCur:
        outputMatrix = []
        outputMatrix.append(row.getValue('cluster'))
        outputMatrix.append(row.getValue('Point_X'))
        outputMatrix.append(row.getValue('Point_Y'))
        writeFileHandle.writerow(outputMatrix)
    writeFile.close()
    del row
    del searchCur
    print 'Finished!'





